import logging

from flask import Flask
from flask_appbuilder import AppBuilder, SQLA
from flask_appbuilder.menu import Menu
from flask_login import LoginManager

from logging.config import fileConfig
import os

from app.controller.sec import MySecurityManager
from app.view.indexview import MyIndexView
from config import config

"""
 Logging configuration
"""

logging.basicConfig(format="%(asctime)s:%(levelname)s:%(name)s:%(message)s")
logging.getLogger().setLevel(logging.DEBUG)
#
# app = Flask(__name__)
# app.config.from_object("config")
db = SQLA()
appbuilder = AppBuilder(
    indexview=MyIndexView,
    menu=Menu(reverse=False),
    security_manager_class=MySecurityManager,
)

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
fileConfig('conf/log-app.conf')

def get_logger(name):
    return logging.getLogger(name)


def get_basedir():
    return os.path.abspath(os.path.dirname(__file__))


def get_config():
    return config[os.getenv('FLASK_CONFIG') or 'default']


def create_app(config_name='default'):
    app = Flask(__name__)
    with app.app_context():
        # print(config_name,config)
        app.config.from_object(config[config_name])
        config[config_name].init_app(app)
        login_manager.init_app(app)
        db.init_app(app)
        appbuilder.init_app(app, db.session)
        from . import views  # noqa
        # from .main import main as main_blueprint
        # app.register_blueprint(main_blueprint)
        #
        # from .auth import auth as auth_blueprint
        # app.register_blueprint(auth_blueprint)
        db.create_all()
        appbuilder.post_init()
        # views.fill_gender()

    return app


